# -*- coding: utf-8 -*-

import os
import cgi
import urllib
import sys
import md5
import time
import Cookie
import logging

from django.utils import simplejson
from xml.dom import minidom

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from google.appengine.api import mail
from google.appengine.api import urlfetch
from google.appengine.api.urlfetch_errors import *
from google.appengine.api import users
from google.appengine.ext.db import Key
from google.appengine.ext.db import BadKeyError
from google.appengine.ext.webapp import template
from time import strftime

from alisoft import AliSoftAPI

from baseclass import BaseHandler
from model import Customer
from model import WishList

# login request sent from alisoft
# http://127.0.0.1/login?user_id=16243860&app_id=21733
# &app_instance_id=USERB24287FBB50B9C88A51F4844F2290061
# &token=D7BB62DC381319B767017336B894F1B65C1D7840F3C47E2F03D188993F29621DD250B6703042CE61294C527F79DA9FD4
# &target=
class AliSoftLogin(BaseHandler):
    def get(self):
        template_values = {}
        result = {}
        info = ""
        view = "view_view"
        try:
            api = AliSoftAPI()
            api.appid = self.request.get('app_id')
            api.instanceid = self.request.get('app_instance_id')
            api.target = self.request.get('target')
            api.token = self.request.get('token')
            api.userid = self.request.get('user_id')
            req = api.getReq('alisoft.validateUser')
            req['appId'] = api.appid
            req['appInstanceId'] = api.instanceid
            req['token'] = api.token
            req['userId'] = api.userid
            req['format'] = 'json'     
            result = api.reqAndRspPlain(req)
            info = str(result.headers.items())+"<hr>"+result.content
            rtn = simplejson.loads(result.content)
            # Check if login successfully            
            if int(rtn['response'])==1:
                # Set ISP authn OK cookie
                self.setCookie('isp', 'alisoft')
                self.setCookie('ispid', api.userid)
                # Get user nick name
                req = api.getReq('alisoft.udb.getDomainLoginId')
                req['domainid'] = '3'
                req['userid'] = api.userid  
                req['format'] = 'json'
                result = api.reqAndRsp(req) 
                user = 'John Doe'
                if int(result['code'])==0:
                    user = result['result']  
                    self.setCookie('ispuser', user)
                else:
                    # Get user nickname failed
                    raise "Get user nickname failed"             
                template_values = {'alisoftauth': True,
                                   'alisoftuser': user,
                                   'alisofttoken': api.token,
                                   'alisoftuserid': api.userid}
                # Get user infor.                 
                customer = Customer.queryByISPAccount('alisoft', api.userid)
                if customer != None:
                    self.setCookie('customer', customer.key())
                self.redirect('/')
            else:
                # Login failed
                raise "Login failed"
        except:
            template_values = {'msg': 'Error: '+str(sys.exc_info())}            
            self.outputTemplate(template_values, view)
            
class LoginEnter(BaseHandler):
    def get(self):
        template_values = {}
        self.outputTemplate(template_values, "login_view")
        
    def post(self):        
        try:
            customer = Customer.queryByEmail(self.request.get('email'))
            if customer.secret == self.request.get('password'):
                self.setCookie('customer', customer.key())
                self.redirect('/')
            else:
                raise 'error'  
        except:
            logging.debug(str(sys.exc_info()))
            template_values = {'msg': 'Error: Login failed'}
            self.outputTemplate(template_values, "login_view")       
            
            
class LoginExit(BaseHandler):
    def get(self):        
        self.deleteCookie('ispuser')
        self.deleteCookie('isp')
        self.deleteCookie('ispid')
        self.deleteCookie('customer')        
        self.redirect('/')
                         

application = webapp.WSGIApplication([('/login/alisoft', AliSoftLogin),
                                      ('/login/enter', LoginEnter),
                                      ('/login/exit', LoginExit)],
                                     debug=True)
    
def main():
    run_wsgi_app(application)

if __name__ == "__main__":
  main()